package com.rtu.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by ljf on 2018/4/15.
 */
public class DateUtil {
    private static final SimpleDateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");

    public static Long getBetweenDays(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return null;
        }
        Long day = (endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    public static Date parseDate(String date) {
        try {
            return YYYY_MM_DD.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String parseDateToString(Date date) {
        try {
            return YYYY_MM_DD.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static List<String> getMonday(Date date1,Date date2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        int i = cal.get(Calendar.DAY_OF_WEEK);
        if (i == 1) {
            cal.set(Calendar.DAY_OF_MONTH,cal.get(Calendar.DAY_OF_MONTH) + 1);
        } else if (i > 2) {
            cal.set(Calendar.DAY_OF_MONTH,cal.get(Calendar.DAY_OF_MONTH) + 9-i);
        }

        int count = getBetweenDays(cal.getTime(), date2).intValue();
        List<String> dateList = new ArrayList<>();
        for (int j = 0; j <= count; j+=7) {
            dateList.add(parseDateToString(cal.getTime()));
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH,7 + day);
        }

        return dateList;
    }
}
